package com.fly.platform.common.lock

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.integration.redis.util.RedisLockRegistry
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.Lock
import javax.annotation.Resource

/**
 * @author Fei
 */
@Component
class RedisLockTemplate : DistributedLockTemplate {

    @Autowired
    private lateinit var redisLockRegistry: RedisLockRegistry

    override fun execute(lockId: String, timeout: Int, unit: TimeUnit, callback: Callback): Any? {

        var lock: Lock? = null
        var getLock = false

        try {
            lock = redisLockRegistry.obtain(lockId)
            getLock = lock.tryLock(timeout.toLong(), unit)

            return if (getLock) {
                // 拿到锁
                callback.onGetLock()

            } else {

                // 未拿到锁
                callback.onTimeout()
            }
        } catch (ex: InterruptedException) {

            Thread.currentThread().interrupt()

        } catch (e: Exception) {

        } finally {

            if (getLock) {

                // 释放锁
                lock!!.unlock()
            }
        }
        return null
    }
}